package com.huluobo.a2201mvvm_imdemo.mvvmdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.huluobo.a2201mvvm_imdemo.R;
import com.huluobo.a2201mvvm_imdemo.databinding.ActivityLoginMvvmdemoBinding;
import com.huluobo.a2201mvvm_imdemo.mvpdemo.UserBean;
import com.huluobo.a2201mvvm_imdemo.net.RetrofitManager;

public class LoginMVVMDemoActivity extends AppCompatActivity {

    ActivityLoginMvvmdemoBinding activityLoginMvvmdemoBinding;

    LoginViewModel loginViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityLoginMvvmdemoBinding = DataBindingUtil.setContentView(this, R.layout.activity_login_mvvmdemo);
        loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);

        //触发请求
        activityLoginMvvmdemoBinding.loginMvvmBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginViewModel.login(
                        activityLoginMvvmdemoBinding.loginMvvmUsername.getText().toString(),
                        activityLoginMvvmdemoBinding.loginMvvmPassword.getText().toString()
                );
            }
        });

        //当LiveData发生改变时,会给出bean类,相当于P层中成功的回调
        loginViewModel.success.observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean userBean) {
                Toast.makeText(LoginMVVMDemoActivity.this, "登录成功:" + userBean.getUsername(), Toast.LENGTH_SHORT).show();
            }
        });

        loginViewModel.failed.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(LoginMVVMDemoActivity.this, "登录失败" + s, Toast.LENGTH_SHORT).show();
            }
        });
    }
}